<template>
	<view class="register-container">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 页面标题 -->
		<view class="page-header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="title">注册账号</view>
		</view>

		<!-- 注册表单 -->
		<view class="register-form">
			<!-- Logo区域 -->
			<view class="logo-section">
				<image class="logo" src="/app/icons/120x120.png" mode="aspectFit" />
				<text class="app-name">校园帮</text>
				<text class="slogan">让校园生活更便捷</text>
			</view>

			<!-- 验证码显示区域 -->
			<view class="verification-display" v-if="showVerificationCode">
				<view class="verification-card">
					<text class="verification-title">验证码</text>
					<text class="verification-code">{{ verificationCodeDisplay }}</text>
					<text class="verification-tip">请将上方验证码输入到下方验证码输入框</text>
				</view>
			</view>
			
			<!-- 重新显示验证码按钮 -->
			<view class="resend-verification" v-if="!showVerificationCode && verificationCodeDisplay">
				<button class="resend-btn" @click="showVerificationCodeAgain">
					重新显示验证码
				</button>
			</view>

			<!-- 输入表单 -->
			<view class="form-section">
				<view class="input-group">
					<view class="input-item">
						<text class="label">手机号</text>
						<input 
							class="input" 
							type="number" 
							placeholder="请输入手机号" 
							v-model="registerForm.phone"
							maxlength="11"
							autocomplete="off"
							autocorrect="off"
							autocapitalize="off"
							spellcheck="false"
						/>
					</view>
					
					<view class="input-item">
						<text class="label">验证码</text>
						<view class="verification-row">
							<input 
								class="input verification-input" 
								type="number" 
								placeholder="请输入验证码" 
								v-model="registerForm.verificationCode"
								maxlength="6"
								autocomplete="off"
								autocorrect="off"
								autocapitalize="off"
								spellcheck="false"
							/>
							<button class="send-code-btn" @click="sendVerificationCode" :disabled="countdown > 0">
								{{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
							</button>
						</view>
					</view>
					
					<view class="input-item">
						<text class="label">密码</text>
						<input 
							class="input" 
							:type="showPassword ? 'text' : 'password'" 
							placeholder="请输入密码" 
							v-model="registerForm.password"
							autocomplete="off"
							autocorrect="off"
							autocapitalize="off"
							spellcheck="false"
						/>
						<view class="password-toggle" @click="togglePassword">
							<text class="toggle-icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
						</view>
					</view>
					
					<view class="input-item">
						<text class="label">确认密码</text>
						<input 
							class="input" 
							:type="showConfirmPassword ? 'text' : 'password'" 
							placeholder="请再次输入密码" 
							v-model="registerForm.confirmPassword"
							autocomplete="off"
							autocorrect="off"
							autocapitalize="off"
							spellcheck="false"
						/>
						<view class="password-toggle" @click="toggleConfirmPassword">
							<text class="toggle-icon">{{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}</text>
						</view>
					</view>
				</view>

				<!-- 注册按钮 -->
				<view class="register-actions">
					<button class="register-btn" @click="handleRegister" :disabled="!canRegister">
						注册
					</button>
					
					<view class="other-actions">
						<text class="action-link" @click="goToLogin">已有账号？去登录</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { http } from '@/utils/request'

// 环境检测函数
const isDev = () => {
	// #ifdef H5
	return import.meta.env.DEV || false
	// #endif
	return false
}

// 响应式数据
const statusBarHeight = ref(0)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
const showVerificationCode = ref(false)
const verificationCodeDisplay = ref('')
let countdownTimer: number | null = null

// 注册表单数据
const registerForm = ref({
	phone: '',
	verificationCode: '',
	password: '',
	confirmPassword: ''
})

// 计算属性：是否可以注册
const canRegister = computed(() => {
	return registerForm.value.phone.length === 11 && 
		   registerForm.value.verificationCode.length === 6 && 
		   registerForm.value.password.length >= 6 && 
		   registerForm.value.password === registerForm.value.confirmPassword
})

// 方法
const goBack = () => {
	uni.navigateBack()
}

const goToLogin = () => {
	uni.navigateTo({
		url: '/pages/my/login/login'
	})
}

const togglePassword = () => {
	showPassword.value = !showPassword.value
}

const toggleConfirmPassword = () => {
	showConfirmPassword.value = !showConfirmPassword.value
}

const showVerificationCodeAgain = () => {
	showVerificationCode.value = true
	// 再次5秒后自动隐藏
	setTimeout(() => {
		showVerificationCode.value = false
	}, 5000)
}

const sendVerificationCode = async () => {
	if (registerForm.value.phone.length !== 11) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return
	}
	
	// 验证手机号格式
	const phoneReg = /^1[3-9]\d{9}$/
	if (!phoneReg.test(registerForm.value.phone)) {
		uni.showToast({
			title: '手机号格式不正确',
			icon: 'none'
		})
		return
	}
	
	try {
		// 显示加载状态
		uni.showLoading({ title: '发送中...' })
		
		// 调用发送验证码API
		const response = await http.post('/zjx/sendVerificationCode', {
			phone: registerForm.value.phone,
			type: 'register'
		})
		
		console.log('发送验证码响应:', response)
		
		// 验证码已发送到用户手机，这里显示提示
		uni.showToast({
			title: '验证码已发送到您的手机',
			icon: 'success'
		})
		
		// 在开发环境下，可以显示测试验证码
		// #ifdef H5
		if (isDev()) {
			const testCode = Math.floor(100000 + Math.random() * 900000).toString()
			verificationCodeDisplay.value = testCode
			showVerificationCode.value = true
			
			// 将测试验证码存储到本地存储
			uni.setStorageSync('tempVerificationCode', testCode)
			uni.setStorageSync('tempVerificationPhone', registerForm.value.phone)
			uni.setStorageSync('tempVerificationTime', Date.now())
		}
		// #endif
		
		// 5秒后自动隐藏验证码显示
		setTimeout(() => {
			showVerificationCode.value = false
		}, 5000)
		
		// 开始倒计时
		countdown.value = 60
		countdownTimer = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) {
				if (countdownTimer) {
					clearInterval(countdownTimer)
					countdownTimer = null
				}
			}
		}, 1000)
		
		// 隐藏加载状态
		uni.hideLoading()
		uni.showToast({
			title: '验证码已发送',
			icon: 'success'
		})
		
	} catch (error: any) {
		console.error('发送验证码失败:', error)
		
		// 确保隐藏加载状态
		uni.hideLoading()
		
		// 显示错误信息
		let errorMessage = '发送验证码失败，请重试'
		if (error?.errMsg) {
			if (error.errMsg.includes('手机号已存在')) {
				errorMessage = '该手机号已被注册'
			} else if (error.errMsg.includes('发送过于频繁')) {
				errorMessage = '发送过于频繁，请稍后再试'
			} else if (error.errMsg.includes('网络')) {
				errorMessage = '网络连接失败，请检查网络'
			}
		} else if (error?.message) {
			errorMessage = error.message
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none'
		})
	}
}

const handleRegister = async () => {
	// 验证表单
	if (!canRegister.value) {
		uni.showToast({
			title: '请完善注册信息',
			icon: 'none'
		})
		return
	}
	
	// 验证手机号格式
	const phoneReg = /^1[3-9]\d{9}$/
	if (!phoneReg.test(registerForm.value.phone)) {
		uni.showToast({
			title: '手机号格式不正确',
			icon: 'none'
		})
		return
	}
	
	// 验证密码长度
	if (registerForm.value.password.length < 6) {
		uni.showToast({
			title: '密码长度不能少于6位',
			icon: 'none'
		})
		return
	}
	
	// 验证两次密码是否一致
	if (registerForm.value.password !== registerForm.value.confirmPassword) {
		uni.showToast({
			title: '两次输入的密码不一致',
			icon: 'none'
		})
		return
	}
	
	// 验证验证码（开发环境下的临时验证）
	// #ifdef H5
	if (isDev()) {
		const storedCode = uni.getStorageSync('tempVerificationCode')
		const storedPhone = uni.getStorageSync('tempVerificationPhone')
		const storedTime = uni.getStorageSync('tempVerificationTime')
		
		if (!storedCode || !storedPhone || !storedTime) {
			uni.showToast({
				title: '请先发送验证码',
				icon: 'none'
			})
			return
		}
		
		if (storedPhone !== registerForm.value.phone) {
			uni.showToast({
				title: '验证码与手机号不匹配',
				icon: 'none'
			})
			return
		}
		
		// 验证码5分钟内有效
		const now = Date.now()
		if (now - storedTime > 5 * 60 * 1000) {
			uni.showToast({
				title: '验证码已过期，请重新发送',
				icon: 'none'
			})
			return
		}
		
		if (storedCode !== registerForm.value.verificationCode) {
			uni.showToast({
				title: '验证码错误',
				icon: 'none'
			})
			return
		}
	}
	// #endif
	
	// 显示加载状态
	uni.showLoading({
		title: '注册中...'
	})
	
	try {
		// 准备注册数据
		const registerData = {
			phone: registerForm.value.phone,
			password: registerForm.value.password,
			code: registerForm.value.verificationCode,
			nickName: `用户${registerForm.value.phone.slice(-4)}` // 使用手机号后4位作为默认昵称
		}
		
		console.log('发送注册请求:', registerData)
		
		// 调用注册接口
		const response = await http.post('/zjx/register', registerData)
		
		console.log('注册响应:', response)
		
		// 清除临时验证码
		uni.removeStorageSync('tempVerificationCode')
		uni.removeStorageSync('tempVerificationPhone')
		uni.removeStorageSync('tempVerificationTime')
		
		// 隐藏验证码显示
		showVerificationCode.value = false
		verificationCodeDisplay.value = ''
		
		// 隐藏加载状态
		uni.hideLoading()
		
		// 根据响应消息显示不同的提示
		const message = response.message || '操作成功！'
		uni.showToast({
			title: message,
			icon: 'success'
		})
		
		// 延迟跳转到登录页面
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/my/login/login'
			})
		}, 1500)
		
	} catch (error: any) {
		console.error('注册过程中发生错误:', error)
		
		// 确保隐藏加载状态
		uni.hideLoading()
		
		// 显示错误信息
		let errorMessage = '注册失败，请重试'
		if (error?.errMsg) {
			if (error.errMsg.includes('手机号已存在')) {
				errorMessage = '该手机号已被注册'
			} else if (error.errMsg.includes('验证码错误')) {
				errorMessage = '验证码错误或已过期'
			} else if (error.errMsg.includes('网络')) {
				errorMessage = '网络连接失败，请检查网络'
			}
		} else if (error?.message) {
			errorMessage = error.message
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none'
		})
	}
}

// 获取系统信息
const getSystemInfo = () => {
	// #ifdef APP-PLUS
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight || 0
	// #endif
	
	// #ifdef H5
	statusBarHeight.value = 0
	// #endif
}

// 生命周期
onMounted(() => {
	getSystemInfo()
})

onUnmounted(() => {
	if (countdownTimer) {
		clearInterval(countdownTimer)
		countdownTimer = null
	}
})

// 全局错误处理
const handleGlobalError = (error: any, context: string) => {
	console.error(`${context} 发生错误:`, error)
	
	// 确保隐藏加载状态
	uni.hideLoading()
	
	// 显示通用错误信息
	uni.showToast({
		title: '操作失败，请重试',
		icon: 'none'
	})
}

// 添加全局错误监听
onMounted(() => {
	// #ifdef H5
	// 监听未捕获的错误
	window.addEventListener('error', (event) => {
		handleGlobalError(event.error, '全局')
	})
	
	// 监听未处理的 Promise 拒绝
	window.addEventListener('unhandledrejection', (event) => {
		handleGlobalError(event.reason, 'Promise')
	})
	// #endif
})
</script>

<style lang="scss" scoped>
.register-container {
	min-height: 100vh;
	height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 0;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.status-bar {
	width: 100%;
	background: transparent;
	flex-shrink: 0;
}

.page-header {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	position: relative;
	flex-shrink: 0;
}

.back-btn {
	width: 50rpx;
	height: 50rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
	backdrop-filter: blur(10rpx);
	z-index: 10;
}

.back-icon {
	font-size: 28rpx;
	color: #fff;
}

.title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: bold;
	color: #fff;
}

.register-form {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 40rpx 30rpx;
}

.logo-section {
	text-align: center;
	margin-bottom: 60rpx;
}

.logo {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	margin-bottom: 20rpx;
}

.app-name {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	color: #fff;
	margin-bottom: 10rpx;
}

.slogan {
	display: block;
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

.verification-display {
	margin-bottom: 40rpx;
}

.verification-card {
	background: rgba(255, 255, 255, 0.15);
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 20rpx;
	padding: 30rpx;
	text-align: center;
	backdrop-filter: blur(10rpx);
}

.verification-title {
	display: block;
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.9);
	margin-bottom: 20rpx;
	font-weight: 500;
}

.verification-code {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	color: #fff;
	margin-bottom: 20rpx;
	letter-spacing: 8rpx;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.verification-tip {
	display: block;
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.7);
	line-height: 1.4;
}

.resend-verification {
	margin-bottom: 30rpx;
	text-align: center;
}

.resend-btn {
	background: rgba(255, 255, 255, 0.1);
	color: rgba(255, 255, 255, 0.8);
	font-size: 24rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 20rpx;
	padding: 15rpx 30rpx;
	backdrop-filter: blur(10rpx);
	transition: all 0.2s ease;
}

.resend-btn:active {
	background: rgba(255, 255, 255, 0.2);
	transform: scale(0.98);
}

.form-section {
	flex: 1;
}

.input-group {
	margin-bottom: 40rpx;
}

.input-item {
	margin-bottom: 30rpx;
	position: relative;
}

.label {
	display: block;
	font-size: 28rpx;
	color: #fff;
	margin-bottom: 15rpx;
	font-weight: 500;
}

.input {
	width: 100%;
	height: 80rpx;
	padding: 0 20rpx;
	background: rgba(255, 255, 255, 0.1);
	border: 2rpx solid rgba(255, 255, 255, 0.2);
	border-radius: 40rpx;
	font-size: 28rpx;
	color: #fff;
	box-sizing: border-box;
	backdrop-filter: blur(10rpx);
}

.input::placeholder {
	color: rgba(255, 255, 255, 0.6);
}

.verification-row {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.verification-input {
	flex: 1;
}

.send-code-btn {
	width: 200rpx;
	height: 80rpx;
	background: rgba(255, 255, 255, 0.2);
	color: #fff;
	font-size: 24rpx;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 40rpx;
	white-space: nowrap;
}

.send-code-btn:disabled {
	background: rgba(255, 255, 255, 0.1);
	color: rgba(255, 255, 255, 0.5);
}

.password-toggle {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	z-index: 10;
}

.toggle-icon {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

.register-actions {
	margin-top: 40rpx;
}

.register-btn {
	width: 100%;
	height: 88rpx;
	background: rgba(255, 255, 255, 0.2);
	color: #fff;
	font-size: 32rpx;
	font-weight: bold;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 44rpx;
	margin-bottom: 30rpx;
	backdrop-filter: blur(10rpx);
	transition: all 0.2s ease;
}

.register-btn:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.98);
}

.register-btn:disabled {
	background: rgba(255, 255, 255, 0.1);
	color: rgba(255, 255, 255, 0.5);
	border-color: rgba(255, 255, 255, 0.2);
}

.other-actions {
	text-align: center;
}

.action-link {
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.8);
	text-decoration: underline;
	cursor: pointer;
}

.action-link:active {
	opacity: 0.8;
}
</style>
